package com.yueya.im.service;

import com.yueya.common.base.BaseService;
import com.yueya.common.util.DateUtils;
import com.yueya.im.dao.tables.UserGroup;
import com.yueya.im.dao.tables.daos.GroupDao;
import com.yueya.im.dao.tables.daos.GroupMessageDao;
import com.yueya.im.dao.tables.daos.UserGroupDao;
import com.yueya.im.dao.tables.pojos.GroupDO;
import com.yueya.im.dao.tables.pojos.GroupMessageDO;
import com.yueya.im.dao.tables.pojos.UserGroupDO;
import org.jooq.Condition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GroupService extends BaseService<GroupDO> {

    @Autowired
    private GroupDao groupDao;
    @Autowired
    private UserGroupDao userGroupDao;
    @Autowired
    private GroupMessageDao groupMessageDao;

    @Override
    public List<Condition> getConditions(GroupDO groupDO) {
        return null;
    }

    public GroupDO fetchGroupById(String groupId) {
        return groupDao.fetchOneByGroupId(Long.valueOf(groupId));
    }

    public List<UserGroupDO> fetchMembers(String groupId) {
        return userGroupDao.fetchByGroupId(Long.valueOf(groupId));
    }

    public GroupDO createGroup(GroupDO groupDO){
        groupDO.setCreateGmt(DateUtils.getCurTimeStamp());
        groupDao.insert(groupDO);
        return groupDO;
    }

    public void saveGroupMsg(GroupMessageDO messageDO){
        groupMessageDao.insert(messageDO);
    }

    public List<GroupDO> findGroups(String userId) {
        return groupDao.findByUserId(Long.valueOf(userId));
    }

    public boolean isMember(String userId,String groupId){
        Condition condition = UserGroup.USER_GROUP.GROUP_ID.eq(Long.valueOf(groupId))
                .and(UserGroup.USER_GROUP.USER_ID.eq(Long.valueOf(userId)));
        return !groupDao.fetchByCondition(condition).isEmpty();
    }
}
